package gbackup.command;

import gbackup.core.RemoteDirectory;
import gbackup.core.RemoteFile;
import gbackup.core.Shell;

import java.util.StringTokenizer;


public class RemoteListCommand extends Command {
	private static final String PARENT = "..";
	private static final String CURRENT = ".";

	private RemoteDirectory _remoteWorkingDirectory = null;

	public RemoteListCommand(Shell shell, String rawCommand) {
		super(shell, rawCommand);
		this._remoteWorkingDirectory = this._shell.getRemoteWorkingDirectory();
	}

	@Override
	public void execute() {
		switch (this._arguments.size()) {
		case 0:
			this._execute(this._remoteWorkingDirectory);
			break;
		case 1:
			RemoteDirectory targetDirectory = this._remoteWorkingDirectory;
			String targetDirectoryPath = this._arguments.get(0);
			StringTokenizer st = new StringTokenizer(targetDirectoryPath, RemoteDirectory.pathSeperator);
			while(st.hasMoreTokens()) {
				String path = st.nextToken();
				
				if(path.equals(RemoteListCommand.PARENT)) {
					targetDirectory = targetDirectory.getParent() == null ? targetDirectory : targetDirectory.getParent();
					continue;
				} else if(path.equals(RemoteListCommand.CURRENT)) {
					continue;
				}
				
				boolean found = false;
				for(RemoteFile f : targetDirectory.getChildern()) {
					if(f.isDirectory() && f.getName().equals(path)) {
						targetDirectory = (RemoteDirectory) f;
						found = true;
						break;
					}
				}
				if(!found) {
					this._outputPrintStream.println("Directory Not Found : [" + this._arguments.get(0) + "]");
					return;
				}
			}
			
			this._execute(targetDirectory);
			break;
		default:
			this._outputPrintStream.println("Invalid Argument : [" + this._rawCommand + "]");
			return;
		}
	}

	private void _execute(RemoteDirectory directory) {
		for (RemoteFile f : directory.getChildern()) {
			if (f.isDirectory())
				this._outputPrintStream.println(f.getName() + RemoteFile.pathSeperator);
			else
				this._outputPrintStream.println(f.getName());
		}
	}
}
